package com.suning.park.admin.mgr.action.service.impl;

import com.suning.park.dto.dao.ActionCouponMapper;
import com.suning.park.dto.dao.ActionMapper;
import com.suning.park.dto.dao.CouponMapper;
import com.suning.park.dto.model.*;
import com.suning.park.admin.util.IdBuilder;
import com.suning.park.admin.util.StringUtil;
import com.suning.park.admin.util.page.PageInfo;
import com.suning.park.admin.bean.ActionVo;
import com.suning.park.admin.enums.ActionStateEnum;
import com.suning.park.admin.mgr.action.service.ActionService;
import com.suning.park.admin.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 活动管理业务层
 * Created by Administrator on 2017/1/18.
 */
@Service(value = "activityService")
public class ActionServiceImpl implements ActionService {

    @Autowired
    ActionMapper actionMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    ActionCouponMapper actionCouponMapper;

    /***
     * 新增注册有礼
     * @param actionVo
     * @throws Exception
     */
    @Transactional
    @Override
    public void addAction(ActionVo actionVo, SysUser sysUser) throws Exception {
        if(actionVo.getCover() == null){
            new Exception("封面图片不能为空");
        }
        if(actionVo.getLogo() == null){
            new Exception("LOGO图片不能为空");
        }
        if(actionVo.getCouponId().length == 0){
            new Exception("关联优惠券不能为空");
        }
        if(actionVo.getCouponNum().length == 0){
            new Exception("关联优惠券数量不能为空");
        }
        //保存活动信息
        MultipartFile cover = actionVo.getCover();
        MultipartFile logo = actionVo.getLogo();
        String coverUrl = "D://images/".concat(cover.getOriginalFilename());
        String logoUrl = "D://images/".concat(logo.getOriginalFilename());
        saveFile(cover.getInputStream(),coverUrl);
        saveFile(logo.getInputStream(),logoUrl);
        Action action = setActionModel(actionVo,sysUser,coverUrl,logoUrl);
        actionMapper.insert(action);
        saveActionCoupon(actionVo,action,sysUser);
    }
    /***
     * 新增注册有礼
     * @param actionVo
     * @throws Exception
     */
    @Transactional
    @Override
    public void editAction(ActionVo actionVo, SysUser sysUser) throws Exception {
        if(actionVo.getCover() == null){
            new Exception("封面图片不能为空");
        }
        if(actionVo.getLogo() == null){
            new Exception("LOGO图片不能为空");
        }
        if(actionVo.getCouponId().length == 0){
            new Exception("关联优惠券不能为空");
        }
        if(actionVo.getCouponNum().length == 0){
            new Exception("关联优惠券数量不能为空");
        }
        //保存活动信息
        MultipartFile cover = actionVo.getCover();
        MultipartFile logo = actionVo.getLogo();
        String coverUrl = "D://images/".concat(cover.getOriginalFilename());
        String logoUrl = "D://images/".concat(logo.getOriginalFilename());
        saveFile(cover.getInputStream(),coverUrl);
        saveFile(logo.getInputStream(),logoUrl);
        Action action = setActionModel(actionVo,sysUser,coverUrl,logoUrl);
        action.setId(actionVo.getId());
        actionMapper.updateByPrimaryKeySelective(action);
        ActionCouponExample example = new ActionCouponExample();
        example.createCriteria().andActionIdEqualTo(action.getId());
        actionCouponMapper.deleteByExample(example);
        saveActionCoupon(actionVo,action,sysUser);
    }

    public void saveActionCoupon(ActionVo actionVo,Action action,SysUser sysUser){
        ActionCoupon actionCoupon = null;
        //保存关联券
        for(int i=0;i<actionVo.getCouponId().length;i++){
            Coupon coupon = couponMapper.selectByPrimaryKey(actionVo.getCouponId()[i]);
            if(coupon.getTotal()<Integer.valueOf(actionVo.getCouponNum()[i]) + coupon.getUseCount()){
                new Exception("优惠券：{}数量不足，请修改发券数量"+coupon.getCouponName());
            }
            actionCoupon = new ActionCoupon();
            actionCoupon.setId(IdBuilder.getID());
            actionCoupon.setNum(Integer.valueOf(actionVo.getCouponNum()[i]));
            actionCoupon.setActionId(action.getId());
            actionCoupon.setCouponId(actionVo.getCouponId()[i]);
            actionCoupon.setOperatorId(sysUser.getUserId());
            actionCoupon.setCreateId(sysUser.getUserId());
            actionCoupon.setCreateName(sysUser.getName());
            actionCoupon.setOperatorName(sysUser.getName());
            actionCoupon.setCouponName(coupon.getCouponName());
            actionCoupon.setCreateTime(new Date());
            actionCoupon.setLastTime(new Date());
            actionCouponMapper.insert(actionCoupon);
            coupon.setUseCount(coupon.getUseCount()+ actionCoupon.getNum());
            coupon.setOperatorId(sysUser.getUserId());
            coupon.setLastTime(new Date());
            coupon.setOperatorName(sysUser.getName());
            couponMapper.updateByPrimaryKeySelective(coupon);
        }
    }

    /***
     * 查询列表
     * @param map
     * @param page
     */
    @Override
    public void queryByPage(Map map, PageInfo page) {
        ActionExample example = new ActionExample();
        ActionExample.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotBlank(map.get("parkId").toString())){
            criteria.andParkIdEqualTo(map.get("parkId").toString());
        }
        if(StringUtil.isNotBlank(map.get("startTime").toString())){
            criteria.andStartTimeGreaterThan(DateUtil.parseDateTime(map.get("startTime").toString()+" 00:00:00","yyyy-MM-dd HH:mm:ss"));
        }
        if(StringUtil.isNotBlank(map.get("endTime").toString())){
            criteria.andEndTimeLessThanOrEqualTo(DateUtil.parseDateTime(map.get("endTime").toString()+" 00:00:00","yyyy-MM-dd HH:mm:ss"));
        }
        if(map.get("actionName") != null && StringUtil.isNotBlank(map.get("actionName").toString())){
            criteria.andActionNameLike(map.get("actionName").toString());
        }
        if(map.get("state") != null && StringUtil.isNotBlank(map.get("state").toString())){
            criteria.andStateEqualTo(map.get("state").toString());
        }
        if(map.get("type") != null && StringUtil.isNotBlank(map.get("type").toString())){
            criteria.andTypeEqualTo(map.get("type").toString());
        }
        criteria.andStateNotEqualTo(ActionStateEnum.DELETE.getValue());
        int total = actionMapper.countByExample(example);
        page.setTotalResult(total);
        example.setLimitStart((page.getCurrentPage()-1) * page.getShowCount());
        example.setLimitRows(page.getShowCount());
        page.setResultObject(actionMapper.selectByExample(example));
    }

    @Override
    public Action getActionById(String id) throws Exception{
        if(!StringUtil.isNotBlank(id)){
            throw new Exception("id不能为空");
        }
       return actionMapper.selectByPrimaryKey(id);
    }

    @Transactional
    @Override
    public void pause(String id) throws Exception {
        if(!StringUtil.isNotBlank(id)){
            throw new Exception("活动id不能为空");
        }
        Action action = new Action();
        action.setId(id);
        action.setState(ActionStateEnum.STOP.getValue());
        actionMapper.updateByPrimaryKeySelective(action);
    }

    @Transactional
    @Override
    public void stop(String id) throws Exception{
        if(!StringUtil.isNotBlank(id)){
            throw new Exception("活动id不能为空");
        }
        Action action = new Action();
        action.setId(id);
        action.setState(ActionStateEnum.DELETE.getValue());
        actionMapper.updateByPrimaryKeySelective(action);
    }
    @Transactional
    @Override
    public void start(String id) throws Exception{
        if(!StringUtil.isNotBlank(id)){
            throw new Exception("活动id不能为空");
        }
        Action action = new Action();
        action.setId(id);
        action.setState(ActionStateEnum.NORMAL.getValue());
        actionMapper.updateByPrimaryKeySelective(action);
    }

    @Override
    public Action queryActionById(String id) throws Exception{
        if(!StringUtil.isNotBlank(id)){
            throw new Exception("活动id不能为空");
        }
        return actionMapper.selectByPrimaryKey(id);
    }

    @Override
    public void handle(String ids, String type) throws Exception{
        if(!StringUtil.isNotBlank(ids)){
            throw new Exception("活动id不能为空");
        }
        if(!StringUtil.isNotBlank(type)){
            throw new Exception("操作类型不能为空");
        }
        Action action = new Action();
        if(ActionStateEnum.NORMAL.getValue().equals(type)){
            action.setState(ActionStateEnum.NORMAL.getValue());
        }else if(ActionStateEnum.DELETE.getValue().equals(type)){
            action.setState(ActionStateEnum.DELETE.getValue());
        }else if(ActionStateEnum.STOP.getValue().equals(type)){
            action.setState(ActionStateEnum.STOP.getValue());
        }
        for(String id : ids.split(",")){
            action.setId(id);
            actionMapper.updateByPrimaryKeySelective(action);
        }
    }

    @Override
    public List<ActionCoupon> queryActionCouponByActionId(String actionId) {
        ActionCouponExample example = new ActionCouponExample();
        example.createCriteria().andActionIdEqualTo(actionId);
        return actionCouponMapper.selectByExample(example);
    }

    /**
     * 封装活动对象
     * @param actionVo
     * @param coverUrl
     * @param logoUrl
     * @return
     */
    public Action setActionModel(ActionVo actionVo,SysUser sysUser,String coverUrl,String logoUrl){
        Action action = new Action();
        action.setActionName(actionVo.getActionName());
        action.setCreateTime(new Date());
        action.setStartTime(DateUtil.parseDateTime(actionVo.getStartDate(),"yyyy-MM-dd HH:mm:ss"));
        action.setEndTime(DateUtil.parseDateTime(actionVo.getEndDate(),"yyyy-MM-dd HH:mm:ss"));
        action.setCoverUrl(coverUrl);
        action.setLogoUrl(logoUrl);
        action.setId(IdBuilder.getID());
        action.setType(actionVo.getType());
        action.setParticipant(actionVo.getParticipant());
        action.setPartNum(actionVo.getPartNum());
        action.setPartType(actionVo.getPartType());
        action.setParkId(actionVo.getParkId());
        action.setParkName(actionVo.getParkName());
        action.setLastTime(new Date());
        action.setState(actionVo.getState());
        action.setOperatorId(sysUser.getUserId());
        action.setOperatorName(sysUser.getName());
        return action;
    }

    /**
     * 保存图片对象
     * @param stream
     * @param path
     * @throws IOException
     */
    public void saveFile(InputStream stream, String path) throws IOException {
        FileOutputStream fs=new FileOutputStream(path);
        byte[] buffer =new byte[1024*1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread=stream.read(buffer))!=-1){
            bytesum+=byteread;
            fs.write(buffer,0,byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
    }

    /***
     * 校验参数
     * @param action
     */
    public void validate(Action action) throws Exception{
        if(!StringUtil.isNotBlank(action.getParkId())){
            throw new Exception("活动广场不能为空");
        }
        if(!StringUtil.isNotBlank(action.getActionName())){
            throw new Exception("活动名称不能为空");
        }
        if(!StringUtil.isNotBlank(action.getType())){
            throw new Exception("活动类型不能为空");
        }
        if(action.getStartTime()==null || action.getEndTime()==null){
            throw new Exception("活动时间不能为空");
        }

        if(!StringUtil.isNotBlank(action.getParkId())){
            throw new Exception("活动广场不能为空");
        }
        if(!StringUtil.isNotBlank(action.getParkId())){
            throw new Exception("活动广场不能为空");
        }
    }
}
